package com.example.demoofimagedownloadapp.model;

import android.content.Context;
import android.graphics.Bitmap;

import android.os.RemoteException;
import android.util.Log;


import com.example.demoofimagedownloadapp.bean.MessageEvent;
import com.example.demoofimagedownloadapp.utils.Constants;
import com.example.downloadservicesdk.listener.DownloadStateListener;
import com.example.downloadservicesdk.manager.DownloadManager;

import org.greenrobot.eventbus.EventBus;

/**
 * @author ts
 */
public class DownloadModel implements IDownloadModel{
    private static final String TAG = DownloadModel.class.getName();
    private static DownloadModel sInstance;
    private Context mContext;
    private DownloadManager mDownloadManager = null;

    public static DownloadModel getInstance(){
        return sInstance;
    }
    public DownloadModel(Context context) {
        sInstance = this;
        mContext = context;
        sInstance.initInstance();
    }

    private void initInstance() {
        mDownloadManager = new DownloadManager(mContext);
        String str = mDownloadManager.getConnect();
        Log.d(TAG, "initInstance: "+str);
    }


    @Override
    public boolean addListener() {
        if(mDownloadManager != null&&mDownloadStateListener != null){
            mDownloadManager.addStateListener(mDownloadStateListener);
            Log.d(TAG, "addListener: DONE");
            return true;
        }
        return false;
    }

    private static boolean START_FIRST = true;
    @Override
    public boolean startDownload() throws RemoteException {
        if(mDownloadStateListener != null){
            if(START_FIRST == true){
                mDownloadManager.startDownload();
                START_FIRST = false;
            } else {
                EventBus.getDefault().post(new MessageEvent(Constants.DOWNLOAD_FLAG_DONE,mDownloadManager.getImage(0)));
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean cancelDownload() throws RemoteException {
        if(mDownloadManager != null){
            mDownloadManager.cancelDownload();
        }
        return false;
    }

    private DownloadStateListener mDownloadStateListener = new DownloadStateListener() {
        @Override
        public void updateProgress(int n) {
            EventBus.getDefault().post(new MessageEvent(Constants.DOWNLOAD_FLAG_PROGRESS,n));
            Log.d(TAG, "updateProgress: "+n);
        }

        @Override
        public void onDownloadDone(Bitmap bitmap) {
            EventBus.getDefault().post(new MessageEvent(Constants.DOWNLOAD_FLAG_DONE,bitmap));
            Log.d(TAG, "onDownloadDone: DONE");
        }
    };
}
